package com.atguigu.flink.day03;

import com.atguigu.flink.beans.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2023/12/2
 * 该案例演示了转换算子--flatmap
 * 需求：如果输入的数据是sensor_1，只打印vc；
 *      如果输入的数据是sensor_2，既打印ts又打印vc。
 */
public class Flink09_transform_flatmap {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<WaterSensor> wsDS = env.fromElements(
            new WaterSensor("sensor_1", 1L, 1),
            new WaterSensor("sensor_1", 2L, 2),
            new WaterSensor("sensor_2", 2L, 2),
            new WaterSensor("sensor_3", 3L, 3)
        );

        wsDS.flatMap(
            new FlatMapFunction<WaterSensor, String>() {
                @Override
                public void flatMap(WaterSensor ws, Collector<String> out) throws Exception {
                    if("sensor_1".equals(ws.id)){
                        out.collect(ws.id + ":" + ws.vc);
                    }else if("sensor_2".equals(ws.id)){
                        out.collect(ws.id + ":" + ws.vc);
                        out.collect(ws.id + ":" + ws.ts);
                    }

                }
            }
        ).print();

        env.execute();
    }
}
